<template>
  <div id="app">
    <div class="titbody">
      <div class="tit">
        <img
          :src="$store.state.logoImg"
          class="logo-img"
          alt=""
          @click="$router.push('/')"
        />
        <div class="fbbtn" @click="fabuInfo">我要发布信息</div>
      </div>
      <div class="titlist">
        <div class="t_item" @click="$router.push('/')">首页</div>
        <div class="t_item" @click="showPage = 1">信息列表</div>
        <div class="t_item" @click="showPage = 2">关于我们</div>
      </div>
    </div>
    <div class="bodyBox">
      <!-- 信息列表 -->
      <div class="infoList" v-if="showPage ==1">
        <div
          class="item"
          v-for="(item, index) in listData"
          :key="index + 'fbinfo'"
          @click="goInfo(item)"
        >
          <img v-if="item.thumbnail" :src="item.thumbnail" class="i_img" alt="" />
          <img v-else src="@/assets/images/imgerr2.png" class="i_img" alt="" />
          <!-- <Avatar shape="square" class="i_img" :src="item.thumbnail" icon="ios-image-outline" size="large" /> -->
          <div class="rig">
            <div class="titl">
              <div class="t_l">
                {{ item.title }}
              </div>
              <div class="t_r">{{ item.createTime }}</div>
            </div>
            <div class="t_info" v-html="item.content">
            </div>
          </div>
        </div>
        <div class="goods-page" style="width: 100%;">
          <Page
            show-total
            @on-change="changePageNum"
            :total="allnum"
            :page-size="10"
          ></Page>
        </div>
      </div>
      <div class="infobox" v-if="showPage ==2">
        <Icon class="back" type="ios-arrow-round-back" @click="showPage = 1" />
        <div class="i_b_tit">{{ infoObj.title }}</div>
        <div class="i_b_con" v-html="infoObj.content"></div>
    </div>
    </div>
    
    <Modal v-model="editMOdel" :title="editTitle" width="60" @on-ok="sendData" :loading="mloading">
      <Form :model="formItem" :label-width="80" ref="sendform" :rules="rules">
        <FormItem label="信息标题" prop="title">
          <Input v-model="formItem.title" placeholder="信息标题"></Input>
        </FormItem>
        <FormItem label="信息头图" prop="thumbnail">
          <Avatar
            v-if="formItem.thumbnail"
            :src="formItem.thumbnail"
            size="80"
          />
          <Avatar v-else icon="ios-analytics" size="80" />
          <Upload
            :show-upload-list="false"
            :on-success="handleSuccess"
            :format="['jpg', 'jpeg', 'png']"
            :action="action"
            :headers="accessToken"
          >
            <Button class="mt_10">上传头图</Button>
          </Upload>
        </FormItem>
        <FormItem label="信息详情" prop="thumbnail">
          <div id="e"></div>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
import E from "wangeditor";
import { infoList, infoAdd, infoEdit } from "@/api/informationDelivery";
import { commonUrl } from "@/plugins/request.js";
import storage from "@/plugins/storage.js";
export default {
  data() {
    return {
      action: commonUrl + "/common/common/upload/file", // 上传接口
      accessToken: {}, // 验证token
      listData: [],
      pageNumber: 1,
      infoModel: false,
      editMOdel: false,
      editTitle: "发布信息",
      editor: "",
      allnum: 0,
      infoObj: {},
      formItem: {
        title: "",
        content: "",
        thumbnail: "",
      },
      rules: {
        title: [{ required: true, message: "信息标题不能为空", trigger: "blur" }],
        content: [{ required: true, message: "信息头图不能为空", trigger: "blur" }],
        thumbnail: [{ required: true, message: "信息详情不能为空", trigger: "blur" }],
      },
      mloading:true,
      showPage:1
    };
  },

  mounted() {
    // 接收id进行查询
    // const id = this.$route.query.id;
    this.getList();
    this.accessToken.accessToken = storage.getItem("accessToken");
    // console.log(new E("#e"))
  },
  methods: {
    handleSuccess(res, file) {
      // 上传成功
      console.log(res, file);
      this.formItem.thumbnail = res.result;
    },
    goInfo(item) {
      this.infoObj = item;
      this.showPage = 2
    },
    getList() {
      var obj = {
        pageNo: this.pageNumber,
        pageSize: 10,
      };
      infoList(obj).then((res) => {
        if (res.code == 200) {
          this.listData = res.result.records;
          this.allnum = res.result.total;
        } else {
          this.$Message.error({
            background: true,
            content: res.message,
          });
        }
        // console.log(res)
      });
    },
    initE() {
      this.editor = new E("#e");

      this.editor.config.uploadFileName = "file";
      this.editor.config.uploadImgServer = this.action; // 你的服务器上传地址
      this.editor.config.uploadImgHeaders = this.accessToken; // 你的服务器toktn
      this.editor.config.uploadImgHooks = {
        before: function (xhr, editor, files) {
          // 图片上传之前触发
          // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，files 是选择的图片文件
          // 如果返回的结果是 {prevent: true, msg: 'xxxx'} 则表示用户放弃上传
          // return {
          //     prevent: true,
          //     msg: '放弃上传'
          // }
        },
        success: function (xhr, editor, result) {
          // 图片上传并返回结果，图片插入成功之后触发
          // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
          console.log(result);
        },
        fail: function (xhr, editor, result) {
          // 图片上传并返回结果，但图片插入错误时触发
          // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
        },
        error: function (xhr, editor) {
          // 图片上传出错时触发
          // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
        },
        timeout: function (xhr, editor) {
          // 图片上传超时时触发
          // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
        },

        // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
        // （但是，服务器端返回的必须是一个 JSON 格式字符串！！！否则会报错）
        customInsert: function (insertImg, result, editor) {
          // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
          // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果

          // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
          console.log(result);
          var url = result.result;
          insertImg(url);

          // result 必须是一个 JSON 格式字符串！！！否则报错
        },
      };

      //这里各位小伙伴可以查询官网，根据自己的需求进行菜单栏调整
      this.editor.config.menus = [
        "head", // 标题
        "bold", // 粗体
        "fontSize", // 字号
        "fontName", // 字体
        "italic", // 斜体
        "underline", // 下划线
        "strikeThrough", // 删除线
        "foreColor", // 文字颜色
        "backColor", // 背景颜色
        "link", // 插入链接
        "list", // 列表
        "justify", // 对齐方式
        "quote", // 引用
        "emoticon", // 表情
        "image", // 插入图片
        "table", // 表格
        "code", // 插入代码
        "undo", // 撤销
        "redo", // 重复
      ];
      this.editor.create();
      this.editor.config.onchange = (html) => {
        console.log(html);
        this.formItem.content = html
        // this.info_ = html; // 绑定当前逐渐地值
        // this.$emit("change", this.info_); // 将内容同步到父组件中
      };
    },

    sendData() {
        var obj = {
            title: this.formItem.title,
            content: this.formItem.content,
            thumbnail: this.formItem.thumbnail,
        }
      this.$refs.sendform.validate((valid) => {
        if (valid) {
            // console.log(123)
            infoAdd(obj).then(res=>{
                if(res.code==200){
                    this.editMOdel = false;
                    this.mloading = true;
                    this.$Message.success('添加成功')
                    this.getList()
                }else{
                    // this.editMOdel = false;
                    // this.mloading = true;
                    this.$Message.error(res.result)
                    setTimeout(() => {
                    this.mloading = false
                }, 300);
                setTimeout(() => {
                    this.mloading = true
                }, 500);
                    }
                // console.log(res)
            }).error(err=>{
                console.log(err)
            });
        } else {
            setTimeout(() => {
                this.mloading = false
            }, 300);
            setTimeout(() => {
                this.mloading = true
            }, 500);
        }
      });
     
    },
    fabuInfo() {
        if (storage.getItem('accessToken')) {
            this.editMOdel = true;
            this.editTitle = "发布信息";
            if (this.editor == "") {
                this.initE();
            }
      } else {
        this.$Modal.confirm({
          title: '请登录',
          content: '<p>请登录后执行此操作</p>',
          okText: '立即登录',
          cancelText: '继续浏览',
          onOk: () => {
            this.$router.push({
              path: '/login',
              query: {
                rePath: this.$router.history.current.path,
                query: JSON.stringify(this.$router.history.current.query)
              }
            });
          }
        });
      }
      
    },
    changePageNum(val) {
      this.pageNumber = val;
      //   this.getGoodsList();
    },
  },
};
</script>

<style lang="scss" scoped>
#app {
  min-height: 100vh;
  .titbody {
    padding: 15px 300px;
    background-color: #fff;
    .tit {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .logo-img {
        max-width: 150px;
        cursor: pointer;
      }
      .fbbtn {
        font-size: 16px;
        text-align: center;
        width: 140px;
        padding: 10px;
        background-color: orangered;
        color: white;
        cursor: pointer;
        border-radius: 10px;
      }
    }
    .titlist {
      margin-top: 30px;
      display: flex;
      align-items: center;
      .t_item {
        display: inline-block;
        font-size: 18px;
        color: #000;
        margin-right: 40px;
        cursor: pointer;
      }
    }
  }

  .bodyBox {
    width: 70vw;
    margin-left: calc(15vw);
    min-width: 1000px;
    // background-color: aqua;
    padding-bottom: 30px;
    margin-top: 30px;
    .infoList {
      .item:last-child {
        border-bottom: 1px solid #666;
      }
      .item:hover {
        background-color: #eee;
        cursor: pointer;
      }
      .item {
        padding: 30px;
        display: flex;
        align-items: flex-start;
        background-color: #fff;
        border-top: 1px solid #666;
        .i_img {
          width: 100px;
          height: 100px;
          margin-right: 10px;
          display: block;
        }
        .rig {
          .titl {
            display: flex;
            align-items: center;
            justify-content: space-between;
            width: calc(70vw - 170px);
            .t_l {
              font-size: 20px;
              font-weight: bold;
            }
          }
          .t_info {
            margin-top: 10px;
            font-size: 14px;
            display: -webkit-box; /* 设置为WebKit内核的弹性盒子模型 */
            -webkit-box-orient: vertical; /* 垂直排列 */
            -webkit-line-clamp: 2; /* 限制显示两行 */
            overflow: hidden; /* 隐藏超出范围的内容 */
            text-overflow: ellipsis; /* 使用省略号 */
          }
        }
      }
    }
    .infobox{
        background-color: #fff;
        padding: 20px 30px;
        position: relative;
        .back{
            position: absolute;
            left: 10px;
            top: 10px;
            font-size: 30px;
            cursor: pointer;
        }
        .i_b_tit{
            text-align: center;
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 20px;
           
        }
    }
  }
}
</style>
